package com.xdf.ecommerce.service.async;

import com.xdf.ecommerce.constant.AsyncTaskStatusEnum;
import com.xdf.ecommerce.vo.AsyncTaskInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 监控异步任务的执行
 * @author chanchaw
 * @create 2025-10-28 14:45
 */
@Aspect
@RequiredArgsConstructor
@Slf4j
@Component
public class AsyncTaskMonitor {
    private final AsyncTaskManager taskManager;

    /**
     * 异步任务执行的环绕切面
     * @param proceedingJoinPoint
     * @return
     */
    @Around("execution(* com.xdf.ecommerce.service.async.AsyncServiceImpl.*(..))")
    public Object taskHandle(ProceedingJoinPoint proceedingJoinPoint){
        String taskId = proceedingJoinPoint.getArgs()[1].toString();// 方法AsyncServiceImpl.asyncGoodsInfo第二个参数是 taskId

        // 更新异步任务的状态为：正在运行
        AsyncTaskInfo asyncTaskInfo = taskManager.getAsyncTaskInfo(taskId);
        asyncTaskInfo.setStatus(AsyncTaskStatusEnum.RUNNING);
        taskManager.setTaskInfo(asyncTaskInfo);

        // 启动任务
        AsyncTaskStatusEnum status;
        Object result;
        try {
            result = proceedingJoinPoint.proceed();
            status = AsyncTaskStatusEnum.SUCCESS;
        } catch (Throwable ex){
            result = null;
            status = AsyncTaskStatusEnum.FAILED;
            log.error("异步任务 [{}] 出现异常：[{}]", taskId, ex.getMessage());
        }
        asyncTaskInfo.setEndTime(LocalDateTime.now());
        asyncTaskInfo.setStatus(status);
        long millis = Duration.between(asyncTaskInfo.getStartTime(), asyncTaskInfo.getEndTime()).toMillis();
        asyncTaskInfo.setTotalTime(millis + "ms");
        taskManager.setTaskInfo(asyncTaskInfo);

        return result;
    }
}
